import React, { useState } from "react";
import {
  Divider,
  Collapse,
  Table,
  Input,
  InputNumber,
  Form,
  Typography,
  Popconfirm,
  Progress,
  List,
  Card,
} from "antd";
import {
  AppstoreAddOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";

interface Item {
  key: string;
  name: string;
  description: string;
  process: number;
}

const originData: Item[] = [
  {
    key: "1",
    name: "react",
    description: "New York No. 1 Lake Park",
    process: 25,
  },
  {
    key: "2",
    name: "ts",
    description: "New York No. 1 Lake Park",
    process: 50,
  },
  {
    key: "3",
    name: "redux",
    description: "New York No. 1 Lake Park",
    process: 75,
  },
  {
    key: "4",
    name: "router",
    description: "New York No. 1 Lake Park",
    process: 100,
  },
];

const nextData = [
  {
    title: "temc 平台",
    content: "集群管理平台",
  },
  {
    title: "demo 自动驾驶",
    content: "汽车驾驶",
  },
  {
    title: "label 样本标记",
    content: "机器学习",
  },
];

const WeeklyWork = () => {
  const initKeys: string | string[] = ["1"];
  const [keys, setKeys] = useState(initKeys);
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [count, setCount] = useState(originData.length);
  const [editingKey, setEditingKey] = useState("");

  const { Panel } = Collapse;

  const callback = (key: string | string[]) => {
    // console.log(key);
    const value = key as string[];
    setKeys([...value]);
    cancel();
  };

  const genExtra = (key: string) => {
    return (
      keys.includes(key) && (
        // <AppstoreAddOutlined />
        <AppstoreAddOutlined
          onClick={(event) => {
            // If you don't want click extra trigger collapse, you can prevent this:
            event.stopPropagation();

            const num = count + 1;
            setCount(num);

            const newItem: Item = {
              key: String(num),
              name: "",
              description: "",
              process: 0,
            };
            data.push(newItem);

            setData([...data]);
            edit(newItem);
          }}
        />
      )
    );
  };

  const getCardExtra = () => (
    <>
      <EditOutlined style={{ marginRight: "10px", cursor: "pointer" }}>
        编辑
      </EditOutlined>
      <DeleteOutlined style={{ cursor: "pointer" }}>删除</DeleteOutlined>
    </>
  );

  const isEditing = (record: Item) => record.key === editingKey;

  const edit = (record: Partial<Item> & { key: React.Key }) => {
    form.setFieldsValue({ name: "", description: "", process: "", ...record });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey("");
  };

  const remove = (record: Item) => {
    setData(data.filter((item) => item.key !== record.key));
  };

  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as Item;

      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };

  const columns = [
    {
      title: "任务",
      dataIndex: "name",
      editable: true,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: "描述",
      dataIndex: "description",
      editable: true,
    },
    {
      title: "完成度",
      dataIndex: "process",
      editable: true,
      render: (process: number) => (
        <Progress
          type="circle"
          strokeColor={{
            "0%": "#108ee9",
            "100%": "#87d068",
          }}
          width={36}
          percent={process}
        />
      ),
    },
    {
      title: "操作",
      dataIndex: "operation",
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{ marginRight: 8 }}
            >
              保存
            </Typography.Link>
            <Popconfirm title="确定取消" onConfirm={cancel}>
              <Typography.Link>取消</Typography.Link>
            </Popconfirm>
          </span>
        ) : (
          <span>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => edit(record)}
              style={{ marginRight: 8 }}
            >
              编辑
            </Typography.Link>
            <Popconfirm title="确定删除?" onConfirm={() => remove(record)}>
              <Typography.Link>删除</Typography.Link>
            </Popconfirm>
          </span>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        inputType: col.dataIndex === "process" ? "number" : "text",
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
    editing: boolean;
    dataIndex: string;
    title: any;
    inputType: "number" | "text";
    record: Item;
    index: number;
    children: React.ReactNode;
  }

  const EditableCell: React.FC<EditableCellProps> = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    const inputNode = inputType === "number" ? <InputNumber /> : <Input />;

    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            {inputNode}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  return (
    <div>
      <Divider orientation="left">周任务列表</Divider>
      <Collapse
        defaultActiveKey={keys}
        onChange={callback}
        expandIconPosition="left"
      >
        <Panel header="本周工作内容" key="1" extra={genExtra("1")}>
          <Form form={form} component={false}>
            <Table
              components={{
                body: {
                  cell: EditableCell,
                },
              }}
              columns={mergedColumns}
              expandable={{
                expandedRowRender: (record) => (
                  <p style={{ margin: 0 }}>{record.description}</p>
                ),
                rowExpandable: (record) => record.name !== "Not Expandable",
              }}
              dataSource={data}
              pagination={{ position: [] }}
            />
          </Form>
        </Panel>
        <Panel header="下周工作计划" key="2" extra={genExtra("2")}>
          <List
            grid={{ gutter: 16, column: 4 }}
            dataSource={nextData}
            renderItem={(item) => (
              <List.Item>
                <Card extra={getCardExtra()} title={item.title}>
                  {item.content}
                </Card>
              </List.Item>
            )}
          />
        </Panel>
      </Collapse>
    </div>
  );
};

export { WeeklyWork };
